/**
 * @description 商品期货 持仓
 * @author zht
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { TableC, CollectC, ExportC } from '../../../../comps';
import SetColumns from '../common/SetColumns';
import _ from 'lodash';
import config from '../../../../comps/business/tradingMarket/config';

@connect(({ positionInquiryM, loading, globalM }) => ({
  globalM,
  positionInquiryM,
  loading,
}))
export default class OptionC extends PureComponent {
  constructor(props) {
    super(props);
    this.scrollx = 0;
    this.newColumns = [];
    this.state = {
      search: {},
      columns: [],
      dataSource: [],
      page: 1,
      pageSize: 20,
      total: 0,
      account: {},
      treeData: [],
      checkedKeys: [],
      scrollx: 0,
    };
  }
  componentDidMount() {
    const { dispatch, optionArgs } = this.props;
    // 查表头信息
    dispatch({
      type: 'positionInquiryM/queryShowCol',
      payload: {
        type: 'Trade_Ana_Option_Hold_Info',
      },
    });
    this.setState(
      {
        search: optionArgs,
      },
      () => {
        this.getTableData();
      },
    );
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    const init = !this.props.optionArgs ? '' : JSON.stringify(this.props.optionArgs);
    const initN = !nextProps.optionArgs ? '' : JSON.stringify(nextProps.optionArgs);
    if (init != initN) {
      this.setState(
        {
          search: nextProps.optionArgs,
        },
        () => {
          this.getTableData();
        },
      );
    }
  }
  //分页切换
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        page: current,
        pageSize: pageSize,
      },
      () => {
        this.getTableData('pageChange');
      },
    );
  };

  //查询表格数据
  getTableData = (type) => {
    const { dispatch } = this.props;
    const { page, pageSize, search } = this.state;
    const params = {};
    params.pageSize = pageSize;
    if (type != 'pageChange') {
      //点击查询按钮 重置页码
      this.setState({
        page: 1,
      });
      params.page = 1;
    } else {
      //点击页码切换时候调用
      params.page = page;
    }

    //列表数据
    dispatch({
      type: 'positionInquiryM/queryOptionTable',
      payload: {
        ...params,
        ...search,
      },
      callback: (res) => {
        res.data &&
          res.data.map((item, key) => {
            item.key = key;
          });
        this.setState({
          dataSource: res.data,
          total: res.total,
        });
      },
    });

    if (type != 'pageChange') {
      //获取统计信息
      dispatch({
        type: 'positionInquiryM/getSearchTotal',
        payload: {
          ...search,
          type: '28',
        },
        callback: (data) => {
          this.setState({
            account: data,
          });
        },
      });
    }
  };

  // 导出参数调整
  changeSearch() {
    const { search } = this.state;
    let newSearch = _.cloneDeep(search);
    if (newSearch && newSearch.fundId) {
      newSearch.fundId = newSearch.fundId.join(',');
    }
    return newSearch;
  }

  render() {
    const {
      positionInquiryM: { columnsInfo, checkedKeysInfo },
      loading,
      globalM: { dataDictionary },
    } = this.props;
    const { search, account = {} } = this.state;
    const columns = _.cloneDeep(columnsInfo[17].columns);
    this.newColumns = columns.filter((item) => item.display == true);
    if (this.newColumns && this.newColumns.length > 10) {
      const a = this.newColumns.length;
      this.scrollx = a * 150;
    } else {
      this.scrollx = 0;
    }

    this.newColumns.map((item) => {
      if (['dataDt', 'opexerBegDate', 'opexerEndDate'].includes(item.key)) {
        item.type = 'date';
      }
      if (item.key == 'lCurrentAmount') {
        item.type = 'number';
      }

      if (['costPrice', 'cost', 'marketValue', 'enFloatProfit', 'unitValue'].includes(item.key)) {
        item.type = 'money';
      }
      if (['marketValue', 'enFloatProfit'].includes(item.key)) {
        item.toFixed = 2;
      }
      if (item.key == 'posType') {
        //持仓类型
        item.render = (text, record) => {
          switch (text) {
            case 'ZQZC':
              return '证券资产';
              break;
            case 'ZQFZ':
              return '证券负债';
              break;
            default:
              return '--';
          }
        };
      }
      if (item.key == 'futureFlag') {
        //交易属性
        item.render = (val, record) => {
          switch (val) {
            case 'PT':
              return '普通';
              break;
            case 'XY':
              return '信用';
              break;
            case 'B':
              return '多头';
              break;
            case 'S':
              return '空头';
              break;
            default:
              return '--';
          }
        };
      }
      if (item.key == 'jysc') {
        item.render = (text, record) => {
          if (record?.exchangeCode) {
            let findvalue = config.filter((item) => {
              return item.value == record.exchangeCode;
            });
            if (findvalue && findvalue.length > 0) {
              return findvalue[0].title;
            } else {
              return '--';
            }
          } else {
            return '--';
          }
        };
      }
      if (item.key == 'exerMode') {
        //行权方式
        item.render = (text, record) => {
          return dataDictionary?.TRADE_ANA_OPTION_EXERMODE?.find((item) => item.code == text)?.value || '--';
        };
      }
      if (item.key == 'operationType') {
        //期权权利类型
        item.render = (text, record) => {
          return dataDictionary?.TRADE_ANA_OPTION_OPRIGHTTYPE?.find((item) => item.code == text)?.value || '--';
        };
      }
    });

    return (
      <div>
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <div style={{ flex: 1, margin: '20px 27px 20px 0' }}>
            <CollectC
              dataSource={[
                {
                  name: '认购多头开仓数量', //名称
                  value: account.subscribeDuoNum, //数值
                },
                {
                  name: '认购空头开仓数量', //名称
                  value: account.subscribeKongNum, //数值
                },
                {
                  name: '认沽多头开仓数量', //名称
                  value: account.putDuoNum, //数值
                },
                {
                  name: '认沽空头开仓数量', //名称
                  value: account.putKongNum, //数值
                },
                {
                  name: '市值', //名称
                  value: account.marketValue, //数值
                  toFixed: 2,
                },
                {
                  name: '浮动盈亏', //名称
                  value: account.enFloatProfit, //数值
                  toFixed: 2,
                },
              ]}
              type='2'
              isloading={loading.effects['positionInquiryM/getSearchTotal']}
            />
          </div>
          <div style={{ display: 'flex' }}>
            <div>
              <ExportC style={{ marginTop: '10px' }} url='api/v1/tradeAnaOptionFutureHoldInfo/export' search={this.changeSearch()} />
            </div>
            <div style={{ marginLeft: '5px', marginTop: '10px' }}>
              <SetColumns type='17' parameter='Trade_Ana_Option_Hold_Info' checkedKeysInfo={checkedKeysInfo} />
            </div>
          </div>
        </div>
        <TableC
          columns={this.newColumns || []}
          dataSource={this.state.dataSource || []}
          onChange={this.handleTableChange}
          current={this.state.page}
          pageSize={this.state.pageSize}
          total={this.state.total}
          selfScrollY={true}
          scroll={{ x: this.scrollx }}
          loading={loading.effects['positionInquiryM/queryOptionTable']}
          rowKey={'key'}
        />
      </div>
    );
  }
}
